import { create } from 'zustand'
import { setItem, removeItem, getItem, USER_INFO_KEY, TOKEN_KEY } from '@/utils/storage'
import { loginApi } from '@/api/login'
import { getUserInfoApi } from '@/api/user'
import { ILoginData } from '@/types/login'
import { IUserInfo } from '@/types/user'

export interface IUserStore {
  /**
   * token
   */
  token: string
  /**
   * 用户信息
   */
  userInfo: IUserInfo
  /**
   * 登录
   * @param loginData
   * @returns
   */
  login: (loginData: ILoginData) => Promise<void>
  /**
   * 退出登录
   * @returns
   */
  logout: () => Promise<void>
  /**
   * 获取用户信息
   * @returns
   */
  getUserInfo: () => void
}

export const useUserStore = create<IUserStore>(set => ({
  token: getItem(TOKEN_KEY) || '',
  userInfo: getItem(USER_INFO_KEY) || {},
  login: loginData => {
    console.log('values:', loginData)

    return new Promise(async resolve => {
      const { data } = await loginApi(loginData)
      // 缓存到store
      set({ token: data })
      // 保存到本地
      setItem(TOKEN_KEY, data)
      resolve()
    })
  },
  logout: () => {
    return new Promise(resolve => {
      set({ token: '' })
      removeItem(TOKEN_KEY)
      resolve()
    })
  },
  getUserInfo: () => {
    getUserInfoApi().then(res => {
      set({ userInfo: res.data })
      setItem(USER_INFO_KEY, res.data)
    })
  }
}))
